const app = getApp();
var WxParse = require('../../lib/wxParse/wxParse.js');
const api = require('../../config/api.js');
let that;
Page({
  data: {
    RootUrl: api.RootUrl,
    ImgRootUrl: app.globalData.ImgRootUrl,
    id: 0,
    goods: {},
    gallery: [],
    attribute: [],
    issueList: [],
    comment: [],
    brand: {},
    specificationList: [],
    productList: [],
    relatedGoods: [],
    cartGoodsCount: 0,  //购物车商品数量
    userHasCollect: 0,
    number: 1,    //加入购物车默认数量
    price:0,      //规格商品价格
    store_nums:0, //库存数量
    checkedSpecText: '请选择规格数量',
    checkedValues :[],     //已选规格集
    openAttr: false,
    noCollectImage: "/static/images/icon_collect.png",          //未收藏
    hasCollectImage: "/static/images/icon_collect_checked.png", //收藏
    collectBackImage: "/static/images/icon_collect.png"         //返回箭头
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    that = this;
    this.setData({
      id: parseInt(options.id)
    });
    this.getGoodsInfo();
    //购物车商品数量 
    app.cart.CartGoodsCount().then(function (res) {
      that.setData({
        cartGoodsCount: res.data.cartTotal.goodsCount
      });
    }).catch((err) => {
      console.log(err)
    });
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  onShareAppMessage: function () {
    return {
      title: app.globalData.title + '-' + that.data.goods.name,
      desc: that.data.goods.description,
      path: '/pages/goods/goods?id=' + this.data.id
    }
  },
  //获取商品数据
  getGoodsInfo: function () {
    app.util.request(api.GoodsDetail, { id: that.data.id }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          goods: res.data.info,
          gallery: res.data.gallery,
          attribute: res.data.attribute,
          issueList: res.data.issue,
          comment: res.data.comment,
          brand: res.data.brand,
          specificationList: res.data.specificationList,
          productList: res.data.productList,
          userHasCollect: res.data.userHasCollect
        });
        //是否收藏
        if (res.data.userHasCollect == 1) {
          that.setData({
            'collectBackImage': that.data.hasCollectImage
          });
        } else {
          that.setData({
            'collectBackImage': that.data.noCollectImage
          });
        }
        //商品详情
        WxParse.wxParse('goodsDetail', 'html', res.data.info.content, that);
        //大家都在看
        that.getGoodsRelated();
        //规格集初始化
        let len = res.data.specificationList.length;
        for (let k = 0; k < len; k++)  that.data.checkedValues.push({ valueId: 0, name: res.data.specificationList[k].name });
      }
    });

  },
  //大家都在看
  getGoodsRelated: function () {
    app.util.request(api.GoodsRelated, { id: that.data.id }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          relatedGoods: res.data.goodsList,
        });
      }
    });
  },
  //点击sku规格回调
  clickSkuValue: function (event) {
    //console.log(event);
    let specValueId = event.currentTarget.dataset.valueId;  //*规格id
    let specName = event.currentTarget.dataset.name;        //*规格名字
    let specValue = event.currentTarget.dataset.value;      //*规格值
    let i = event.currentTarget.dataset.i;  //*specificationList的index
    let j = event.currentTarget.dataset.j;  //*value的index
    //初始化规格对象
    let _checkedObj = {
      valueId: 0,
      name: specName,
      value: specValue,
      i: i,
      j: j,
    };
    //规格列表选中处理
    let _specificationList = this.data.specificationList;
    if (_specificationList[i].value[j].checked) {
      //如已选、取消
      _specificationList[i].value[j].checked = false;
    } else {
      //选中当前点击
      _specificationList[i].value[j].checked = true;
      _checkedObj.valueId = specValueId;
      //取消兄弟节点
      if (this.data.checkedValues[i].valueId != 0) {
        let ii = this.data.checkedValues[i].i;
        let jj = this.data.checkedValues[i].j;
        _specificationList[ii].value[jj].checked = false;
      }
    }
    //选中的规格集
    this.data.checkedValues[i] = _checkedObj;
    this.setData({
      'specificationList': _specificationList
    });

    //已选规格信息显示
    let checkedValue = this.data.checkedValues.filter(function (v) {
      if (v.valueId != 0) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v.value;
    });
    if (checkedValue.length > 0) {
      this.setData({
        'checkedSpecText': checkedValue.join(' ')
      });
    } else {
      this.setData({
        'checkedSpecText': '请选择规格数量'
      });
    }
    //计算其他状态
    this.setSpecValueStatus();
  },
  //根据已选规格值，计算其它状态【价格、库存、立即购买、加入购物车 等等】
  setSpecValueStatus: function () {
    //完整规格？
    if (!this.isCheckedAllSpec()) {
      //规格不完整，清除规格价格、库存
      this.setData({
        price: 0,
        store_nums:0
      });
      return false;
    }
    //console.log('规格ok', this.data.checkedValues);
    //根据选中的规格，判断是否有对应的Product信息
    let checkedProduct = this.getCheckedProductItem(this.getCheckedSpecKey());
    //console.log('选中Product', checkedProduct);
    if (!checkedProduct || checkedProduct.length <= 0) {
      //找不到对应的product信息，提示用户
      wx.showToast({
        image: '/static/images/icon_error.png',
        title: '货品不存在',
        mask: true
      });
      return false;
    }else{
      //接口获取货品数据
      app.util.get(api.GetProduct, { product_id: checkedProduct[0].id, random: Math.random() }).then(function (res) {
        let _res = res;
        if (_res.errno == 0) {
          //货品价格：会员价优先
          let price = _res.data.group_price ? _res.data.group_price : _res.data.sell_price;
          that.setData({
            price: price,
            store_nums: parseInt(_res.data.store_nums)    //货品库存
          });
          //实时：验证库存
          if (_res.data.store_nums < that.data.number) {
            //修改数量
            that.setData({
              //number: _res.data.store_nums
            });
            //提示剩余库存
            app.util.showToast('库存不足，剩余：' + _res.data.store_nums);            
          }
        } else {
          //接口获取货品数据失败
          app.util.showToast(_res.error);
        }
      });
    }
  },
  //判断规格是否选择完整
  isCheckedAllSpec: function () {
    return !this.data.checkedValues.some(function (v) {
      if (v.valueId == 0) {
        return true;
      }
    });
  },
  //获取已选规格key的拼接串
  getCheckedSpecKey: function () {
    let checkedValueId = this.data.checkedValues.map(function (v) {
      return v.valueId;
    });
    return checkedValueId.join('_');
  },
  //获取已选规格的货品信息
  getCheckedProductItem: function (key) {
    let CheckedProductItem = this.data.productList.filter(function (v) {
      if (v.goods_spec_ids == key) {
        return true;
      } else {
        return false;
      }
    });
    return CheckedProductItem;
  },
  //打开 规格弹窗
  switchAttrPop: function () {
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr
      });
    }
  },
  //关闭 规格弹窗
  closeAttr: function () {
    this.setData({
      openAttr: false,
    });
  },
  //添加、取消收藏
  addCannelCollect: function () {
    app.util.get(api.CollectAddOrDelete, { goods_id: this.data.id, random: Math.random() })
      .then(function (res) {
        let _res = res;
        if (_res.errno == 0) {
          if (_res.data.type == 'add') {
            that.setData({
              'collectBackImage': that.data.hasCollectImage
            });
          } else {
            that.setData({
              'collectBackImage': that.data.noCollectImage
            });
          }
          app.util.showToast(_res.data.message);
        } else {
          app.util.showToast(_res.error);
        }
      });
  },
  openCartPage: function () {
    wx.switchTab({
      url: '/pages/cart/cart',
    });
  },
  //加入购物车回调
  addToCart: function () {
    //console.log('已选规格集',this.data.checkedValues);
    if (this.data.openAttr == false) {
      //打开 规格弹窗
      this.setData({
        openAttr: !this.data.openAttr
      });
      //如果是商品：库存量等于商品库存
      if (this.data.specificationList.length == 0){
        that.setData({
          store_nums: parseInt(this.data.goods.store_nums)
        });
      }
    } else {
      //完整规格？
      if (!this.isCheckedAllSpec()) {
        this.data.checkedValues.some(function (v) {
          if (v.valueId == 0) {
            //提示未选规格
            app.util.showToast('请选择：' + v.name);
          }
        });
        return false;
      }
      //根据已选规格，取对应的Product
      let checkedProduct = this.getCheckedProductItem(this.getCheckedSpecKey());
      //console.log('选中Product', checkedProduct);
      if (!checkedProduct || checkedProduct.length <= 0) {
        //无product，提示没有库存 
        wx.showToast({
          image: '/static/images/icon_error.png',
          title: '库存不足',
          mask: true
        });
        return false;
      } 
      //本地 验证库存（未请求接口）
      //说明：因为库存数据是用户选择规格时的库存；在抢购时，如果用户选中规格后长时间不加入购物车，会造成本地库存与线上库存不一致
      if (this.data.store_nums < this.data.number) {
        //提示剩余库存
        app.util.showToast('库存不足，剩余：' + this.data.store_nums);
        return false;
      }

      //添加到购物车
      app.util.request(api.CartAdd, { goodsId: this.data.goods.id, number: this.data.number, productId: checkedProduct[0].id, random: Math.random() }, "POST")
        .then(function (res)  {
          let _res = res;
          if (_res.errno == 0) {
            app.globalData.cartGoodsCount = _res.data.cartTotal.goodsCount;
            that.setData({
              //openAttr: !that.data.openAttr,    //是否关闭属性弹窗？
              cartGoodsCount: _res.data.cartTotal.goodsCount
            });
            //添加购物车 成功
            app.util.showToast('加入购物车成功');
          } else {
            //添加购物车 失败
            app.util.showToast(_res.error);
          }
        });
    }
  },
  cutNumber: function () {
    this.setData({
      number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
    });
  },
  addNumber: function () {
    this.setData({
      number: this.data.number + 1
    });
  }
})